import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useUserStore } from '@/store/user'

// 创建 axios 实例
const request: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求重试配置
const retryConfig = {
  retries: 3,
  retryDelay: 1000,
  shouldRetry: (error: any) => {
    return (
      error.code === 'ECONNABORTED' ||
      error.code === 'ERR_NETWORK' ||
      (error.response && error.response.status >= 500)
    )
  }
}

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers['Authorization'] = `Bearer ${userStore.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    // 如果是文件下载，直接返回response
    if (response.config.responseType === 'blob') {
      const contentType = response.headers['content-type']
      if (contentType && contentType.includes('application/json')) {
        // 如果返回的是json格式的错误信息
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.onload = () => {
            try {
              const result = JSON.parse(reader.result as string)
              // ElMessage.error(result.message || '导出失败')
              reject(result)
            } catch (e) {
              reject(new Error('导出失败'))
            }
          }
          reader.readAsText(response.data)
        })
      }
      return response.data
    }

    const res = response.data

    if (res.code === 200) {
      return res
    }

    // token 过期
    if (res.code === 401) {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
    }

    // ElMessage.error(res.message || '请求失败')
    return Promise.reject(new Error(res.message))
  },
  async (error) => {
    // 处理重试逻辑
    const config = error.config as AxiosRequestConfig & { _retryCount?: number }
    if (!config || !retryConfig.shouldRetry(error)) {
      ElMessage.error(error.message || '请求失败')
      return Promise.reject(error)
    }

    config._retryCount = config._retryCount || 0
    if (config._retryCount >= retryConfig.retries) {
      ElMessage.error('请求失败，请检查网络连接')
      return Promise.reject(error)
    }

    config._retryCount++
    await new Promise(resolve => setTimeout(resolve, retryConfig.retryDelay))

    return request(config)
  }
)

export default request 